import { Inject, Middleware } from '@midwayjs/core'
import { Context, NextFunction } from '@midwayjs/koa'
import { httpError } from '@midwayjs/core'
import { JwtService } from '@midwayjs/jwt'
import { pathWhiteList } from '../config/whiteList.js'

@Middleware()
export class JwtMiddleware {
  @Inject()
  jwtService: JwtService

  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      // 判断下有没有校验信息
      if (!ctx.headers['authorization']) {
        throw new httpError.UnauthorizedError('未登录')
      }
      // 从 header 上获取校验信息
      const parts = ctx.get('authorization').trim().split(' ')

      if (parts.length === 2 && /^Bearer$/i.test(parts[0])) {
        const token = parts[1]
        try {
          const { payload }: any = this.jwtService.verifySync(token, {
            complete: true
          })

          ctx.headers['user'] = payload
        } catch (error) {
          throw new httpError.UnauthorizedError('登录已过期')
        }
      } else throw new httpError.UnauthorizedError('未登录')

      const result = await next()
      return result
    }
  }

  ignore(ctx: Context): boolean {
    // 下面的路由将忽略此中间件
    return pathWhiteList.includes(ctx.path)
  }
}
